package com.hbt.android.kotlin.http

import android.util.Log
import okhttp3.Interceptor
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer

class LoggingInterceptor: Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val startTime = System.nanoTime()
        val request = chain.request()
        val response = chain.proceed(request)

        val buffer = Buffer()
        request.body?.writeTo(buffer)
        val requestBody = buffer.readUtf8()


        Log.e(
            "okhttp",
            String.format("sending request %s with params %s", request.url, requestBody)

        )

        val bussinessData = response.body?.toString()?:"response body null"
        val mediaType = response.body?.contentType()
        val newBody = ResponseBody.create(mediaType, bussinessData)
        val newResponse = response.newBuilder().body(newBody).build()

        val endTime = System.nanoTime()

        Log.e(
            "okhttp",
            String.format(
                "Received response for %s in $.1fms %s",
                request.url,
                (endTime - startTime) / 1e6,
                bussinessData

            )
        )
        return newResponse
    }

}